const chalk = require("chalk");

function getDate() {
  const now = new Date();

  const month = `${now.getMonth() + 1}`.padStart(2, '0');
  const date = `${now.getDate()}`.padStart(2, '0');
  const hour = `${now.getHours()}`.padStart(2, '0');
  const minute = `${now.getMinutes()}`.padStart(2, '0');
  const second = `${now.getSeconds()}`.padStart(2, '0');
  const millisecond = `${now.getMilliseconds()}`.padStart(3, '0');

  return `${now.getFullYear()}-${month}-${date}-${hour}-${minute}-${second}-${millisecond}`
}

// 控制台打印进度
let resolvedCount = 0;

function progressLogger() {
  const total = global.__shouldCheckFileCount;
  resolvedCount++

  if (resolvedCount > total) {
    resolvedCount = total;
  }

  const percent = (resolvedCount) / total * 30; // █，░
  let str = ''.padEnd(percent, '█');

  str = str.padEnd(30, '░');
  process.stdout.write('\033[44;30m WAIT \033[40;34m ' + str + ' ' + (total > resolvedCount ? '\r' : '\n') + '\033[0m');

  if (total === resolvedCount) {
    profilerUseTime()
  }
}

// 计算耗时
let enableProfiler = false

function profilerUseTime() {
  if (!enableProfiler) {
    console.time('耗时');
    enableProfiler = true;
  } else {
    console.timeEnd('耗时');
    enableProfiler = false;
  }
}

// 合并配置
function mergeConfig(path) {
  const config = require(path)

  const environment = process.env.useConfig;

  if (environment && config.extraConfig.hasOwnProperty(environment)) {
    const newConfig = {...config};
    const extraConfig = config.extraConfig[environment]
    delete newConfig.environment;

    for (let prop in extraConfig) {
      newConfig[prop] = extraConfig[prop]
    }

    return newConfig
  }

  delete config.extraConfig;
  return config;
}

/**
 * 日志打印
 * @param {string} msg
 * @param {'log' | 'error'| 'warn'} type
 */
function notice(msg, type = 'log') {
  if (type === 'error') {
    console.log(chalk.red(msg));
    return;
  }

  if (type === 'warn') {
    console.log(chalk.yellow(msg));
    return;
  }

  console.log(msg);
}

function validConfig(options) {
  if (!options.includes && !options.fileList) {
    notice('缺少文件入口，请配置 includes 或 fileList', 'error')
    process.exit()
  }

  if (!options?.dealFn) {
    notice('缺少处理函数 dealFn', 'error')
    process.exit()
  }

  if (typeof options.dealFn !== 'function') {
    notice('dealFn 只能设置函数!', 'error')
    process.exit()
  }

  if (options?.filterFiles && typeof options.filterFiles !== 'function') {
    notice('filterFiles只能设置函数', 'error')
    process.exit()
  }

  if (options?.after && typeof options.after !== 'function') {
    notice('after只能设置函数', 'error')
    process.exit()
  }
}

module.exports = {
  profilerUseTime,
  getDate,
  progressLogger,
  mergeConfig,
  notice,
  validConfig
}
